package TestSparkConversionOperator.KeyValuePairRDD;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.List;

public class SparkReduceByKey {
    public static void main(String[] args) {
        /**
         * reduce有减少、压缩之意，
         * reduceByKey的作用就是对相同key的数据进行处理，
         * 最终每个key只保留一条记录。例如求每一个key的所有值的和、求每一个key的所有值的最大值/最小值
         */

        SparkConf sparkConf = new SparkConf().setAppName("SparkReduceByKey").setMaster("local");
        JavaSparkContext sc = new JavaSparkContext(sparkConf);
        List<String> data = Arrays.asList("2021-10,48", "2021-10,47", "2021-10,47","2021-11,50");
        JavaRDD<String> rdd1 = sc.parallelize(data);

        JavaPairRDD<String, Integer> pairRDD = rdd1.mapToPair(new PairFunction<String, String, Integer>() {
            @Override
            public Tuple2<String, Integer> call(String s) throws Exception {

                return new Tuple2<>(s.split(",")[0], Integer.parseInt(s.split(",")[1]));
            }
        });

        JavaPairRDD<String, Integer> newRdd = pairRDD.reduceByKey(new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer integer, Integer integer2) throws Exception {
                if(integer > integer2){
                    return integer;
                }else {
                    return integer2;
                }
//                return integer > integer2 ? integer : integer2;
//                return integer + integer2;
            }
        });
        System.out.println(newRdd.collect());

    }
}
